<?php

class ProductController extends AdminController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to access 'index' and 'view' actions.
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated users to access all actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionUpload($id=null){
		$file = CUploadedFile::getInstanceByName('file');
		// Do your business ... save on file system for example,
		// and/or do some db operations for example
		$model = Gadget::model()->findByPk($id);
		
		$tempFile =  md5(time()).$file->getName();
		$model->imageUrl = strtolower($tempFile);
		$tempFile = strtolower($tempFile);
		
		$file->saveAs('uploads/products/'.$tempFile);
		// return the new file path
		$model->save();
		echo Yii::app()->baseUrl.'/uploads/products/fill/400-400/'.$tempFile;
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model=$this->loadModel($id);
		$Gadgetcondition = Gadgetcondition::model()->findAll();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Gadget']))
		{
			
			$model->attributes=$_POST['Gadget'];
			$model->categoryId=$_POST['categoryId'];
			$model->urlKey = Gadgetcategory::model()->__filterAlias($model->name);
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('view',array(
			'model'=>$model,
			'Gadgetcondition'=>$Gadgetcondition,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Gadget;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Gadget']))
		{
			$model->attributes=$_POST['Gadget'];
			$model->categoryId=$_POST['categoryId'];
			$model->urlKey = Gadgetcategory::model()->__filterAlias($model->name);
			if($model->save()){
				Gadgetquote::model()->deleteAllByAttributes(array(
					'gadgetId'=>$model->id
				));
				$gadgetcondition = Gadgetcondition::model()->findAll();
				if(!empty($gadgetcondition)){
					foreach($gadgetcondition as $key=>$value){
						$gadgetQuoteModel = new Gadgetquote;
						$gadgetQuoteModel->gadgetId = $model->id;
						$gadgetQuoteModel->conditionId = $value->id;
						$gadgetQuoteModel->price = 0;
						$gadgetQuoteModel->isActive = 1;
						$gadgetQuoteModel->save();
					}
				}
				$this->redirect(array('update','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	public function actionUpdateQuote($id){
		if(isset($_POST))
		{
			
			Gadgetquote::model()->deleteAllByAttributes(array(
				'gadgetId'=>$id
			));
			foreach($_POST['Quote'] as $key=>$value){
				$model = new Gadgetquote;
				$model->gadgetId = $id;
				$model->conditionId = $key;
				$model->price = $value;
				$model->isActive = 1;
				$model->save();
			}
			
			$this->redirect(array('update','id'=>$id));
		}
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$Gadgetcondition = Gadgetcondition::model()->findAll();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Gadget']))
		{
			
			$model->attributes=$_POST['Gadget'];
			$model->categoryId=$_POST['categoryId'];
			$model->urlKey = Gadgetcategory::model()->__filterAlias($model->name);
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
			'Gadgetcondition'=>$Gadgetcondition,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$gadgetModels = Gadgetquote::model()->findAllByAttributes(array('gadgetId'=>$id));
		foreach ($gadgetModels as $gadgetModel) {
			$customerQuotes = Customerquote::model()->findAllByAttributes(array('quoteId'=>$gadgetModel->id));
			if($customerQuotes) {
				foreach ($customerQuotes as $customerQuote) {
					Customerquote::model()->findByPk($customerQuote->id)->delete();
					Customer::model()->findByPk($customerQuote->customerId)->delete();
				}
			}
			Gadgetquote::model()->findByPk($gadgetModel->id)->delete();
		}
		$this->loadModel($id)->delete();
		
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new Gadget('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Gadget']))
			$model->attributes=$_GET['Gadget'];

		$this->render('admin',array(
			'model'=>$model,
		));
		// $dataProvider=new CActiveDataProvider('Gadget');
		// $this->render('index',array(
			// 'dataProvider'=>$dataProvider,
		// ));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Gadget('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Gadget']))
			$model->attributes=$_GET['Gadget'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Gadget the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Gadget::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Gadget $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='gadget-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
